package com.example.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.util.RedisUtil;
import com.example.dao.user.UserDAO;
import com.example.domain.UserDO;
import com.example.query.UserQuery;
import com.example.service.UserService;
import com.example.web.vo.UserQueryVO;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 * 核心职责：实现具体业务逻辑，确保业务事务的完整性和一致性
 * 
 * @author AI Assistant
 * @since 1.0.0
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserDAO userDAO;
    
    @Autowired
    private RedisUtil redisUtil;
    
    @Override
    public IPage<UserQueryVO> queryUserPage(UserQuery query) {
        try {
            log.info("开始查询用户列表，查询条件：{}", query);
            
            // 创建分页对象
            Page<UserDO> page = new Page<>(query.getPageNum(), query.getPageSize());
            
            // 执行分页查询
            IPage<UserDO> userPage = userDAO.selectUserPage(page, query);
            
            // 转换为VO对象
            List<UserQueryVO> voList = userPage.getRecords().stream()
                    .map(this::convertToVO)
                    .collect(Collectors.toList());
            
            // 创建返回的分页对象
            Page<UserQueryVO> resultPage = new Page<>(userPage.getCurrent(), userPage.getSize(), userPage.getTotal());
            resultPage.setRecords(voList);
            
            log.info("用户列表查询完成，共查询到{}条记录", userPage.getTotal());
            return resultPage;
            
        } catch (Exception e) {
            log.error("查询用户列表异常，查询条件：{}", query, e);
            throw new RuntimeException("查询用户列表失败", e);
        }
    }
    
    @Override
    public UserQueryVO getUserById(Long id) {
        try {
            log.info("开始查询用户详情，用户ID：{}", id);
            
            // 先从用户缓存Redis中获取
            String cacheKey = "user:" + id;
            UserQueryVO cachedUser = redisUtil.getUserCache(cacheKey, UserQueryVO.class);
            if (cachedUser != null) {
                log.info("从用户缓存Redis中获取用户信息，用户ID：{}", id);
                return cachedUser;
            }
            
            // 缓存未命中，从数据库查询
            UserDO userDO = userDAO.selectUserById(id);
            if (userDO == null) {
                log.warn("用户不存在，用户ID：{}", id);
                return null;
            }
            
            UserQueryVO userVO = convertToVO(userDO);
            
            // 将结果写入用户缓存Redis
            redisUtil.setUserCache(cacheKey, userVO, 30, TimeUnit.MINUTES);
            log.info("用户详情查询完成并缓存，用户ID：{}", id);
            return userVO;
            
        } catch (Exception e) {
            log.error("查询用户详情异常，用户ID：{}", id, e);
            throw new RuntimeException("查询用户详情失败", e);
        }
    }
    
    /**
     * 将DO对象转换为VO对象
     * 
     * @param userDO 用户DO对象
     * @return 用户VO对象
     */
    private UserQueryVO convertToVO(UserDO userDO) {
        UserQueryVO userVO = new UserQueryVO();
        BeanUtils.copyProperties(userDO, userVO);
        
        // 设置状态描述
        if (userDO.getStatus() != null) {
            userVO.setStatusDesc(userDO.getStatus() == 1 ? "启用" : "禁用");
        }
        
        return userVO;
    }
}
